﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using Dapper;
using DapperExtensions;
using ExaminationSys.DataAccess.Entity;
using SQLinq;
using SQLinq.Dapper;

namespace ExaminationSys.DataAccess.Repository
{
    public class PaperInfoRepository : Repository<PaperInfo>
    {
        public PaperInfoRepository(SqlConnection context)
            : base(context)
        {
            db = context;
        }
        private SqlConnection db;
        public override PaperInfo GetById(dynamic id)
        {
            return base.ObjectSet.Get<PaperInfo>(db, id, null, null);
        }
    }
    public class PaperInfoService
    {
        private PaperInfoService()
        {
        }

        public PaperInfo Get(Guid id)
        {
            using (var db = DataContent.DBServer())
            {
                IUnitOfWork work = new UnitOfWork(db);
                var result = work.PaperInfo.GetById(id);
                return result;

            }
        }

        public bool ExistsPaperInfo(Guid sectionId)
        {
            using (var db = DataContent.DBServer())
            {
                var result =
                    db.Query<int>("SELECT count(1) FROM SectionPaper pi1 WHERE pi1.SectionInfoID='" + sectionId + "' and Status <> 0").
                        FirstOrDefault();
                return result > 0;
            }
        }

        public List<PaperInfo> GetPaperInfoBySectionId(Guid sectionId)
        {
            using (var db = DataContent.DBServer())
            {

                var result = db.Query(from p in new SQLinq<PaperInfo>()
                                      where p.SectionID == sectionId && p.Status == 1
                                      select p).ToList();
                return result;

            }
        }

        public bool CheckPaperNo(string paperno, Guid id)
        {
            using (var db = DataContent.DBServer())
            {
                var pg = new PredicateGroup { Operator = GroupOperator.And, Predicates = new List<IPredicate>() };
                pg.Predicates.Add(Predicates.Field<PaperInfo>(f => f.PaperNo, Operator.Eq, paperno));
                pg.Predicates.Add(Predicates.Field<PaperInfo>(f => f.ID, Operator.Eq, id, true));
                IUnitOfWork work = new UnitOfWork(db);
                var result = work.PaperInfo.GetList(pg).FirstOrDefault();
                return result != null;
            }
        }

        public List<PaperInfo> GetAll()
        {
            using (var db = DataContent.DBServer())
            {
                IUnitOfWork work = new UnitOfWork(db);
                var result = work.PaperInfo.GetList();
                return result.ToList();
            }
        }

        public bool Delete(List<string> ids)
        {
            if (ids == null || ids.Count == 0) return false;
            bool flag = false;
            using (var db = DataContent.DBServer())
            {
                int retCode = 0;
                foreach (var id in ids)
                {
                    retCode = db.Execute(@"update PaperInfo set Status=0 where ID=@TmpId",
                                         new[] { new { TmpId = id } });
                    if (retCode <= 0)
                    {
                        break;
                    }
                }
                flag = true;
            }
            return flag;
        }

        public bool Lock(List<string> ids, int _lock)
        {
            if (ids == null || ids.Count == 0) return false;
            bool flag = false;
            using (var db = DataContent.DBServer())
            {
                int retCode = 0;
                foreach (var id in ids)
                {
                    retCode = db.Execute(@"update PaperInfo set Lock=@lk where ID=@TmpId",
                                         new[] { new { lk = _lock, TmpId = id } });
                    if (retCode <= 0)
                    {
                        break;
                    }
                }
                flag = true;
            }
            return flag;
        }

        public bool Update(PaperInfo entity)
        {
            using (var db = DataContent.DBServer())
            {
                IUnitOfWork work = new UnitOfWork(db);
                return work.PaperInfo.Update(entity);
            }
        }
        public dynamic Insert(PaperInfo entity)
        {
            using (var db = DataContent.DBServer())
            {
                IUnitOfWork work = new UnitOfWork(db);
                return work.PaperInfo.Insert(entity, null);
            }
        }

        public List<PaperInfo> GetListByPage(string sqlwhere, string orderbyFiled, int pagesize, int pageindex, out int totalPage, out int totalRecord)
        {
            if (string.IsNullOrWhiteSpace(orderbyFiled))
                throw new ArgumentNullException("orderbyFiled");

            if (string.IsNullOrWhiteSpace(sqlwhere))
                sqlwhere = " 1=1";
            using (var db = DataContent.DBServer())
            {
                var obj = new
                {
                    TableName = "PaperInfo",
                    Fields = "*",
                    OrderField = orderbyFiled,
                    sqlWhere = sqlwhere,
                    pageSize = pagesize,
                    pageIndex = pageindex,
                };

                var dynamicParam = new DynamicParameters(obj);
                dynamicParam.Add("TotalPage", null, DbType.Int32, ParameterDirection.Output, 32);
                dynamicParam.Add("TotalRecord", 0, DbType.Int32, ParameterDirection.Output, 32);

                var items = db.Query<PaperInfo>("PagingRecord", dynamicParam, null, true, null, CommandType.StoredProcedure);
                totalPage = dynamicParam.Get<int>("TotalPage");
                totalRecord = dynamicParam.Get<int>("TotalRecord");
                return items.ToList();
            }
        }
    }
}
